/**
 * 
 */
package com.flute.framework.search.highlight;

import java.util.ArrayList;
import java.util.List;

import com.flute.tools.util.PinyinUtil;
import com.flute.tools.util.StringUtil;

/**
 * @author HongJun Tang
 *
 */
public class PinYinSplitedMarkStrategy implements IMarkStrategy {

	/* (non-Javadoc)
	 * @see com.flute.search.mark.IMarkStrategy#getMarked(java.lang.String, java.lang.String)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public MarkPosition[] getMarked(String keyword, String searchString) {
		if (!StringUtil.isCharOrNumberString(keyword)) {
			return new MarkPosition[]{};
		}
		List<MarkPosition> set = new ArrayList<MarkPosition>();
		List<List> sslist = PinyinUtil.getPinyinList(searchString);
		keyword = PinyinUtil.getPinyinString(keyword);
		List<int[]> reint = indexArray(keyword, sslist);
		if (reint != null && !StringUtil.isCharOrNumberString(searchString)) {
			for (int[] inar : reint) {
				MarkPosition mp = new MarkPosition();
				mp.setStart(inar[0]);
				mp.setSource(searchString);
				mp.setEnd(inar[1]);
				set.add(mp);
			}
		}
		return set.toArray(new MarkPosition[] {});
	}
	
	@SuppressWarnings("unchecked")
	public List<int[]> indexArray(String kwl, List<List> ssl){
		List<int[]> relist = new ArrayList<int[]>();
		int sslength = ssl.size();
		for (int i = 0; i < sslength; i++) {
			Object[] kwls = ssl.get(i).toArray();
			for (int j = 0; j < kwls.length; j++ ) {
				boolean bo = false;
				int p = 0;
				if (kwl.indexOf((String)kwls[j]) == 0) {
					String sb = "";
					while((j + p) < kwls.length) {
						String str = sb + (String)kwls[j+p];
						p++;
						if(kwl.indexOf(str) != 0){
							bo = false;
							break;
						}
						if (kwl.equals(str)) {
							bo = true;
							break;
						}
						sb = str;
					}
					if (bo) {
						bo = false;
						relist.add(new int[]{j,j + p});
						
					}
				} 
			}
		}
		
		return relist;
	}
	
	
	public static void main(String args[]){
		//System.out.println(PinyinUtil.getPinyinString("nihao"));
		
		//System.out.println("tanghongjun".indexOf("tangjun"));
		 for (MarkPosition mp : new PinYinSplitedMarkStrategy().getMarked(
				"nihao", "你好你好你好")) {
			System.out.println(mp.getStart());
			System.out.println(mp.getEnd());
			System.out.println(mp.getSource());
		}
	}

}
